package com.feng.gulimall.ware.service.impl;

import com.alibaba.nacos.api.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feng.common.constant.WareConstant;
import com.feng.gulimall.ware.entity.PurchaseDetailEntity;
import com.feng.gulimall.ware.service.PurchaseDetailService;
import com.feng.gulimall.ware.service.WareSkuService;
import com.feng.gulimall.ware.vo.MergeVo;
import com.feng.gulimall.ware.vo.PurchaseDoneVo;
import com.feng.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.common.utils.PageUtils;
import com.feng.common.utils.Query;

import com.feng.gulimall.ware.dao.PurchaseDao;
import com.feng.gulimall.ware.entity.PurchaseEntity;
import com.feng.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        String status = (String) params.get("status");
        LambdaQueryWrapper<PurchaseEntity> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isBlank(key)){
            wrapper.and((w) -> {
                w.eq(PurchaseEntity::getId, key).or().like(PurchaseEntity::getAssigneeName, key).or().like(PurchaseEntity::getPhone, key);
            });
        }
        if (!StringUtils.isBlank(status)){
            wrapper.eq(PurchaseEntity::getStatus, status);
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        LambdaQueryWrapper<PurchaseEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.CREATED.getCode())
                    .or().eq(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.ASSIGNMENT.getCode());

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);

    }

    @Transactional
    @Override
    public void mergePurchaseItems(MergeVo mergeVo) {
        // 如果存在数据，就修改，不存在就添加
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        PurchaseEntity byId = this.getById(purchaseId);
        if (byId.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
        || byId.getStatus() == WareConstant.PurchaseItemStatusEnum.ASSIGNMENT.getCode()){
            // 更新
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = mergeVo.getItems().stream().map((item) -> {

                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item);   // 设置当前id
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);  // 设置采购单的id
                // 跟新状态
                purchaseDetailEntity.setStatus(WareConstant.PurchaseItemStatusEnum.ASSIGNMENT.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        }else {
            throw new RuntimeException("当前采购单已经被领取");
        }
    }

    @Transactional
    @Override
    public void receive(List<Long> ids) {
        List<PurchaseEntity> purchaseEntities = ids.stream().map((id) -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter((purchaseEntity) -> {
            return purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNMENT.getCode();
        }).collect(Collectors.toList());

        purchaseEntities.stream().forEach((purchaseEntity) -> {
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setStatus(WareConstant.PurchaseStatusEnum.ACCEPT.getCode());
            purchase.setUpdateTime(new Date());
            purchase.setId(purchaseEntity.getId());
            this.updateById(purchase);    // 保存采购单

            // 保存采购需求
            purchaseDetailService.updateDetail(purchaseEntity.getId());
        });


    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        // 判断是否成功采购
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        Boolean flag = true;
        for (PurchaseItemDoneVo item : items) {
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.HASERRO.getCode()){
                flag = false;
            }else {
                // 更新库存
                PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                Integer stock = byId.getSkuNum();
                Long skuId = byId.getSkuId();
                Long wareId = byId.getWareId();
                wareSkuService.updateStock(stock, skuId, wareId);
            }
            // 更新采购需求状态
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntity.setStatus(item.getStatus());
            purchaseDetailService.updateById(purchaseDetailEntity);
        }

        // 更新采购单状态
        Long purchaseId = purchaseDoneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode():
                WareConstant.PurchaseStatusEnum.HASERRO.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

}
